<template>
  <div class="taskReview">
    <courseHeadInfo :courseInfo="courseInfo" />
    <div class="taskReview-content">
      <selectCourses
        :courseInfo="courseInfo"
        :studentList="studentList"
        :myTeachingCourses="myTeachingCourses"
        @changeSelectCourse="changeSelectCourse"
        @handleChangeSelectTaskInfo="handleChangeSelectTaskInfo"
        :gettingStuList="gettingStuList"
        :gettingCourseList="gettingCourseList"
        :confirmLoading="confirmLoading"
      />
      <selectStudent
        :courseInfo="courseInfo"
        :studentList="studentList"
        :selectTaskInfo="selectTaskInfo"
        @changeStudentTaskData="changeStudentTaskData"
        @handleConfirmSelectStu="handleConfirmSelectStu"
        @getStudentDataed="getStudentDataed"
        @loadingStuStudyData="loadingStuStudyData"
        :gettingStuList="gettingStuList"
        @handleSelectClass="handleSelectClass"
        @changeFilterStu="changeFilterStu"
      />
      <div class="taskReviewMain">
        <collapseTask
          :courseInfo="courseInfo"
          :selectTaskInfo="selectTaskInfo"
          :currSelectStudentTaskData="currSelectStudentTaskData"
          @handleChangeReviewStu="handleChangeReviewStu"
          :confirmLoading="confirmLoading"
          ref="taskReviewMain"
        />
      </div>
      <div class="submitReview">
        <submitReview
          :currReviewStu="currReviewStu"
          :selectTaskInfo="selectTaskInfo"
          :gitem="gitem"
          :currSelectStudentTaskData="currSelectStudentTaskData"
          :studentList="studentList"
          @handleAddComment="handleAddComment"
          @changeUserComment="changeUserComment"
          @handleChangeTaskState="handleChangeTaskState"
          :commentList="commentList"
          v-if="gitem"
        />
      </div>
    </div>
  </div>
</template>

<script>
const courseHeadInfo = () =>
  import("@/components/teacherPage/courseHeadInfo/courseHeadInfo");
const selectCourses = () =>
  import("@/views/teacher/taskReview/components/selectCourse");
const selectStudent = () =>
  import("@/views/teacher/taskReview/components/selectStudent");
const collapseTask = () =>
  import("@/views/teacher/taskReview/components/collapseTask");
const submitReview = () =>
  import("@/views/teacher/taskReview/components/submitReview");
import {
  getCourseDetail,
  getCurriculumCourse,
  getCurriculumlist,
} from "@/request/courses";
import { getCurrNoData, getCourseData } from "@/request/teacher";
// import { b } from "@/util/testCourseInfo";
// import { c } from "@/util/testCourseStu";
import { mapState } from "vuex";
import { sortArr } from "@/util/courseData";
import { Session } from"@/util/sessionStorage.js"

export default {
  components: {
    courseHeadInfo,
    selectCourses,
    selectStudent,
    collapseTask,
    submitReview,
  },
  data() {
    return {
      courseInfo: {},
      myTeachingCourses: [],
      studentList: [],
      selectTaskInfo: {
        taskGroup: null,
        task: null,
      },
      gitem: null,
      currSelectStudentTaskData: [], // 当前所选的学生的学习数据
      currReviewStu: null, // 当前批阅的学生
      gettingStuList: false, // 是否正在获取学生列表
      gettingCourseList: false, // 是否正在获取课程列表
      commentList: [],
      confirmLoading: false, // 选择学生组件确认选择时返回的值
      gotClassID: [], // 将已获取的学生的班级ID记录在这
      isGetAllStus: false, // 是否已获取全部学生
      isFilterStu: true, // 是否根据指导教师过滤学生
    };
  },
  watch: {
    // 开启后只要vuex缓存的课程列表数据发生改变 则会影响已缓存的批阅页面的已展开课程
    // myTeaching(n, o) {
    //   this.myTeachingCourses = this.myTeaching;
    // },
  },
  computed: {
    ...mapState({
      userInfo: (state) => state.user.userInfo,
      myTeaching: (state) => state.courses.myTeaching,
    }),
    getCourseQueryData() {
      return this.$route.query.currNo && this.$route.query.courseID;
    },
  },
  created() {
    this.handleInitMyCourseList();
    this.initCoursesInfo();
  },
  methods: {
    // 初始化我的课程列表
    handleInitMyCourseList() {
      this.gettingCourseList = true;
      this.myTeachingCourses = this.myTeaching.map((item) => {
        item.children = [];
        return item;
      });
      this.$nextTick(() => {
        this.gettingCourseList = false;
      });
    },
    // 初始化课程信息或课程列表
    initCoursesInfo() {
      if (!this.myTeaching.length) {
        this.fetchMyTeachingCoursesList();
      } else {
        const timer = setTimeout(() => {
          // this.myTeachingCourses = [...this.myTeaching];
          this.getCoursesDataNotEmpty();
          clearTimeout(timer);
        }, 100);
      }
    },
    // 添加标签
    setTagsViewTitle(name) {
      if (this.$route.path === "/") return;
      const title = this.$route.meta.name;
      const courseName = name.name;
      const route = Object.assign({}, this.$route, {
        title: courseName ? courseName : ` ${title}-${this.$route.params.id}`,
      });
      this.$store.dispatch("tagsView/updateVisitedView", route);
    },
    // 获取所有课程
    fetchMyTeachingCoursesList() {
      this.gettingCourseList = true;
      getCurriculumlist().then((data) => {
        if (data) {
          // res.data = res.data?.filter(
          //   (item) => item.tutorStaffUserID === this.userInfo.userID
          // );
          this.myTeachingCourses =
            [
              ...data?.reverse(),
              // ...res.data?.reverse(),
            ] || [];
          this.$store.commit(
            "courses/changeMyTeachingCourses",
            this.myTeachingCourses
          );
          if (!this.myTeachingCourses.length) {
            this.$antdMessage.warning({
              content: "您没有在授课程！",
            });
          } else {
            this.getCoursesDataNotEmpty();
          }
        } else {
          this.$antdMessage.warning({
            content: "获取我的课程列表失败！",
          });
        }
        this.gettingCourseList = false;
      });
    },
    // 检查获取课程详情的必要参数
    async getCoursesDataNotEmpty() {
      if (!this.getCourseQueryData) {
        this.$antdMessage.warning({
          content: "您未选择课程，请在课程列表中选择！",
        });
      } else {
        const { currNo, courseID, filter } = this.$route.query;
        const { meta } = this.$route;
        if (!currNo || !courseID) return this.$antdMessage.error({content: "缺少获取课程的必要信息;"})
        let  classID = await this.$store.dispatch("class/getClassID", filter)
        // 已获取过所有班级则返回
        this.setTagsViewTitle({ name: meta.name + `-${currNo}` });
        await this.fetchCoursesDeital({
          id: courseID,
          currNo: currNo,
          courseID: courseID,
        });
        this.fetchGetCurrCourseStus({
          currNo: Number(currNo),
          classID: classID,
        });
      }
    },
    // 获取课程详情 同时获取开设课程信息
    fetchCoursesDeital(params) {
      return new Promise((resolve, reject) => {
        // const getCourseDetailInfo = getCourseDetail(params);
        const getCourseDetailInfo = getCourseData(params);
        const getCurriculumCourseInfo = getCurriculumCourse({
          id: params.currNo,
        });
        Promise.all([getCourseDetailInfo, getCurriculumCourseInfo]).then(
          (res) => {
            if (res[1].errno === 0 && res[0]) {
              // res[0].data = b;
              // this.taskSettings = res[1].data.taskSettings;
              this.formatCourseGroupTaskObj(res[0], this);
              res[0].taskSettings = res[1].data.taskSettings;
              let currName = res[1].data.name;
              currName = currName.substring(
                0,
                currName.lastIndexOf("_") == -1
                  ? currName.length
                  : currName.lastIndexOf("_")
              );
              Object.assign(res[0], res[1].data);
              // res[0].data["currNo"] = res[1].data.currNo;
              res[0].currName = currName;
              res[0].name = currName;
              // res[0].data.currDesc = res[1].data.currDesc;
              // res[0].data.tutorStaffUserName = res[1].data.tutorStaffUserName;
              res[0].tutorStaffIconPath = res[1].data.iconPath;
              // res[0].data.classNameList = res[1].data.classNameList;
              // res[0].data.classIDList = res[1].data.classNameList;
              Object.assign( res[0], res[1])
              this.courseInfo = res[0];
              this.setTagsViewTitle({ name: this.courseInfo.name });
              resolve(this.courseInfo);
            } else {
              this.$antdMessage.error({
                content: "获取课程信息失败，请刷新页面！",
              });
            }
          }
        );
      });
    },
    // 格式化任务组、任务字段为chidlren
    formatCourseGroupTaskObj(data, that) {
      if (!data) return;
      that.$set(data, "children", []);
      Object.keys(data.taskGroups).forEach((item) => {
        // 将tasks对象 格式化为数组
        let markTasksArray = [];
        Object.keys(data.taskGroups[item].tasks).forEach((titem) => {
          markTasksArray.push(data.taskGroups[item].tasks[titem]);
          // 将引导文格式化为数组
          let markGuidelineArray = [];
          let guidelines = data.taskGroups[item].tasks[titem].guidelines;
          guidelines &&
            Object.keys(guidelines).forEach((gitem) => {
              markGuidelineArray.push(
                data.taskGroups[item].tasks[titem].guidelines[gitem]
              );
            });
          markGuidelineArray = sortArr(markGuidelineArray, "noInTask");
          that.$set(
            data.taskGroups[item].tasks[titem],
            "oldGuidelines",
            data.taskGroups[item].tasks[titem].guidelines
          );
          that.$set(
            data.taskGroups[item].tasks[titem],
            "guidelines",
            markGuidelineArray
          );
        });
        markTasksArray = sortArr(markTasksArray, "taskNoInGroup");
        data.taskGroups[item].children = markTasksArray;
        data.children.push(data.taskGroups[item]);
      });
      data.children = sortArr(data.children, "groupNoInCourse");
    },
    // 切换课程
    changeSelectCourse(res, unSet) {
      const { currNo, courseID } = res;
      const { params, query } = this.$route
      // this.courseInfo = res;
      !unSet && (query.filter = undefined)
      this.$router.push({
        name: this.$route.name,
        params: Object.assign(params, { id: currNo }),
        query: Object.assign(query, { currNo, courseID }),
      });
    },
    async fetchGetCurrCourseStus(params) {
      this.gettingStuList = true;
      this.gettingCourseList = true;
      const className = await this.$store.dispatch("class/getClassName", params.classID)
      let sList = await this.getLocalStuList(params.classID, className)
      // 获取缓存中的某个班级
      if (sList) {
        if (this.courseInfo.shouldChooseTutor) sList = sList?.filter(item => item.tutorID === this.userInfo.userID)
        this.gettingStuList = false;
        this.gettingCourseList = false;
        let newList = []
        if (params.classID) {
          newList = sList.filter(item => item.classID == params.classID || className ? item.className == className : false)
          this.gotClassID.push(params.classID)
        }
        else newList = sList
        return this.studentList = [...this.studentList, ...sList];
      }
      getCurrNoData(params)
        .then((data) => {
          if (data) {
            // data = c;
            if (this.isFilterStu) {
              // 过滤已有的学生
              data = data.filter(item => !this.studentList.some(sitem => sitem.userID == item.userID))
              if (this.courseInfo.shouldChooseTutor) data = data?.filter(item => item.tutorID === this.userInfo.userID)
            }
          this.studentList = [...this.studentList, ...data];
          this.setSessionStuList(this.studentList)
          } else {
            this.$antdMessage.error({
              content: "获取当前课程的学生列表失败",
            });
          }
          this.gettingStuList = false;
          this.gettingCourseList = false;
          if (params.classID) this.gotClassID.push(params.classID)
        })
        .catch((err) => {
          this.gettingCourseList = false;
        });
    },
    // 获取本地学生列表
    async getLocalStuList(classID, className) {
      const timeout = Session.get("stuListTout")
      const currTime = new Date().getTime()
      if ((timeout - currTime) <= 0) return false
      const sList = await Session.get("stuList")
      let key = this.$route.query.currNo
      if (sList?.[key]) {
        let getClassList = []
        if (classID || className) {
          getClassList = sList[key].filter(item => item.classID == classID || item.className == className)
        } else if (sList[key].length != Number(this.courseInfo.choosedNum)) return false // 如果学生学习数据的数量与选课人数不一致
        else getClassList = sList[key]
        if (getClassList.length) return getClassList
        else return false
      } else return false
    },
    // 缓存学生列表
    async setSessionStuList(data) {
      if (!Array.isArray(data)) return
      let sList = await Session.get("stuList")
      let key = this.$route.query.currNo
      if(sList) {
        if (sList[key]) {
          sList[key] = sList[key].filter(item => !data.some(sitem => sitem.userID == item.userID))
          sList[key] = [...sList[key], ...data]
        } else sList[key] = data
      } else {
        sList = {}
        sList[key] = data
      }
      Session.set('stuList', sList)
      Session.set('stuListTout', new Date().getTime() + 600000)
    },
    // 任务切换
    handleChangeSelectTaskInfo(data) {
      this.currSelectStudentTaskData = [];
      this.currReviewStu = null;
      this.selectTaskInfo = data;
    },
    changeStudentTaskData(data) {
      this.currSelectStudentTaskData = [
        ...data,
        // ...data,
      ];
      // .map((item, index) => {
      //   item.userID = index;
      //   return Object.assign({}, item);
      // });
    },
    // 当前批阅的学生
    handleChangeReviewStu(item, gitem) {
      this.currReviewStu = item;
      this.gitem = gitem;
    },
    handleAddComment(val) {
      if (this.commentList.indexOf(val) == -1) this.commentList.unshift(val);
    },
    // 同步数据
    changeUserComment(obj) {
      const stu = this.studentList.find(
        (item) => item.userID === this.currReviewStu.userID
      );
      if (stu) {
        const task = stu.allTaskResultsInChooseNo.find(
          (item) => item.taskID == this.selectTaskInfo.task.data.taskID
        );
        if (task)
          this.$set(task.guidelineResults, obj.guidelineID, obj.guidelineData);
      }
    },
    // get
    handleConfirmSelectStu(val) {
      this.confirmLoading = val;
    },
    getStudentDataed(data) {
      data.forEach((item) => {
        const findStu = this.studentList.find(
          (sitem) => sitem.userID == item.userID
        );
        if (findStu)
          findStu.allTaskResultsInChooseNo = item.allTaskResultsInChooseNo;
      });
      // this.studentList.forEach(item => {
      // const findStuData = data.find(ditem => ditem.userID === item.userID)
      // if (!findStuData) return
      // let allTask = []
      // const taskGroups = findStuData.taskGroupResults
      // Object.keys(taskGroups).forEach(gkeys => {
      //   const tasks = findStuData.taskGroupResults[gkeys].taskResults
      //   Object.keys(tasks).forEach(tkeys => {
      //     allTask.push(tasks[tkeys])
      //   })
      // })
      // if (findStuData) this.$set(item, "allTaskResultsInChooseNo", allTask)
      // })
    },
    // 正在加载学生当前任务的学习数据
    loadingStuStudyData(data) {
      this.gettingStuList = data;
    },
    // 修改学生列表finishedTaskResultArray的任务状态
    handleChangeTaskState(data, isAllReviewed) {
      const findUser = this.studentList.find(
        (item) => item.userID == data.userID
      );
      if (findUser) {
        const findTask = findUser.finishedTaskResultArray.find(
          (item) => item.taskID == data.taskID
        );
        if (findTask) this.$set(findTask, "reviewState", isAllReviewed);
      }
    },
    // 切换班级
    async handleSelectClass(className) {
      const { currNo, filter } = this.$route.query;
      let cName = className || filter;
      let classID = undefined;
      if (this.isGetAllStus || !filter || filter == "全部") return;
      if (className !== "全部班级") {
        const classList = await this.$store.dispatch("class/gClassList");
        classID = await this.$store.dispatch("class/getClassID", cName)
        if (this.gotClassID.indexOf(classID) !== -1) return;
        // classID && this.gotClassID.push(classID);
      } else {
        this.isGetAllStus = true;
      }
      this.fetchGetCurrCourseStus({
        currNo: Number(currNo),
        classID: classID,
      });
    },
    // 根据指导教师过滤学生
    async changeFilterStu (data) {
      this.studentList = []
      sessionStorage.removeItem('stuList')
      Session.remove('stuListTout')
      this.isFilterStu = data
      const { currNo, filter } = this.$route.query;
      let classID = await this.$store.dispatch("class/getClassID", filter)
      this.fetchGetCurrCourseStus({
        currNo: Number(currNo),
        classID: classID,
      });
    }
  },
};
</script>

<style lang="stylus">
.taskReview {
  .taskReview-content {
    padding-top: 20px;
    min-width: 1200px;
    display: flex;
    justify-content: center;
    background: #ECECEC;

    .taskReviewMain {
      max-width: 700px;
      min-width: 600px;
      // height: 2000px;
    }

    .submitReview {
      margin-left: 13px;
      flex: 1;
      min-width: 150px;
      max-width: 250px;
    }
  }
}
</style>